import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { AuthService } from '../../core/services/auth.service';
import { ToastrService } from 'ngx-toastr';

// 更明确的表单接口定义
interface LoginForm {
  username: FormControl<string | null>;
  password: FormControl<string | null>;
  remember: FormControl<boolean | null>;
}

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  standalone:false
})
export class LoginComponent implements OnInit {
  loginForm: FormGroup<LoginForm>;
  loading = false;
  submitted = false;

  returnUrl: string = '/';  // 默认跳转首页

  constructor(
    private formBuilder: FormBuilder,
    private router: Router,
    private route: ActivatedRoute,
    private authService: AuthService,
    private toastr: ToastrService
  ) {
    this.route.queryParams.subscribe(params => {
      this.returnUrl = params['returnUrl'] || '/';
    })

    // 使用显式类型初始化表单
    this.loginForm = this.formBuilder.nonNullable.group({
      username: ['', Validators.required],
      password: ['', Validators.required],
      remember: [false]
    }) as FormGroup<LoginForm>;
  }

  // 类型安全的访问器
  get usernameControl() {
    return this.loginForm.controls.username;
  }

  get passwordControl() {
    return this.loginForm.controls.password;
  }

  get rememberControl() {
    return this.loginForm.controls.remember;
  }

  onSubmit() {
    this.submitted = true;

    if (this.loginForm.invalid) {
      return;
    }

    this.loading = true;
    this.authService.login(
      this.usernameControl.value!,
      this.passwordControl.value!
    ).subscribe({
      next: () => {
        this.toastr.success('登录成功');
        // 登录成功后跳转回 returnUrl
        this.router.navigateByUrl(this.returnUrl);
      },
      error: (error) => {
        this.toastr.error(error || '登录失败');
        this.loading = false;
      }
    });
  }

  ngOnInit(): void {
  }
}
